<?php if ( ! defined('APPPATH')) exit('No direct script access allowed');
/**
 *      [PinTuXiu] (C)2001-2099 ONightjar.com Pintuxiu.com.
 *      This is NOT a freeware, use is subject to license terms
*/

class attachment_controller extends PZ_Controller{

	public function __construct() {
		parent::__construct();
		$this->authfunctions = array('upload','download');
	}

	public function download(){
		if(!$this->sysperm['allowdownload']){
			$this->message(lang('nopermission','tip'),lang('nopermission','tip'));
			return;
		}
		$aid = $this->param('aid');
		$attachapi = load_api('attachment');
		if($aid&&($attach = $attachapi->getAttachById($aid))){
			$attachapi->updateDownloads($aid);
			load_helper('download');
			$data = file_get_contents(thumburl($attach['attachment'].'.'.$attach['fileext'],false,$attach['cloud'],true));
			force_download($attach['filename'],$data);
		}
	}

	public function upload(){

		$api = load_api('setting');
		$setting = $api->getUploadSetting();

		$userid = $this->cuser['uid'];

		if(!$userid){
			$this->template->content_display("Login first");
			return;
		}

		$POST_MAX_SIZE = ini_get('post_max_size');
		$unit = strtoupper(substr($POST_MAX_SIZE, -1));
		$multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));

		if ((int)$_SERVER['CONTENT_LENGTH'] > $multiplier*(int)$POST_MAX_SIZE && $POST_MAX_SIZE) {
			header("HTTP/1.1 500 Internal Server Error"); // This will trigger an uploadError event in SWFUpload
			echo "POST exceeded maximum allowed size.";
			exit(0);
		}

		$file_name = $userid.'_'.random(20).'';
		$date_dir = 'data/attachments/'.date("Y/m/d/");
		$save_path = BASEPATH . $date_dir;
		(!is_dir($save_path))&&@mkdir($save_path,0777,true);

		$upload_name = "Filedata";
		$max_file_size_in_bytes = $setting['allow_upload_size'];
		$extension_whitelist = explode('|', $setting['allow_upload_type']);

		// Other variables
		$MAX_FILENAME_LENGTH = 260;
		//$file_name = "";
		$file_extension = "";
		$uploadErrors = array(
				0=>lang('upload_success','tip'),
				1=>lang('upload_exceed_phpini','tip'),
				2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
				3=>"The uploaded file was only partially uploaded",
				4=>"No file was uploaded",
				6=>"Missing a temporary folder"
		);
		$valid_chars_regex = '.A-Z0-9_ !@#$%^&()+={}\[\]\',~`-';

		// Validate the upload
		if (!isset($_FILES[$upload_name])) {
			$this->template->content_display("No upload found in \$_FILES for " . $upload_name);
			return;
		} else if (isset($_FILES[$upload_name]["error"]) && $_FILES[$upload_name]["error"] != 0) {
			$this->template->content_display($uploadErrors[$_FILES[$upload_name]["error"]]);
			return;
		} else if (!isset($_FILES[$upload_name]["tmp_name"]) || !@is_uploaded_file($_FILES[$upload_name]["tmp_name"])) {
			$this->template->content_display(lang('upload_function','tip'));
			return;
		} else if (!isset($_FILES[$upload_name]['name'])) {
			$this->template->content_display(lang('upload_no_filename','tip'));
			return;
		}

		// Validate the file size (Warning: the largest files supported by this code is 2GB)
		$file_size = @filesize($_FILES[$upload_name]["tmp_name"]);
		if (!$file_size) {
			$this->template->content_display(lang('upload_size_exception','tip'));
			return;
		}
		if (!$file_size || $file_size > $max_file_size_in_bytes) {
			$this->template->content_display($file_size.' max'.$max_file_size_in_bytes.lang('upload_exceed_max_size','tip'));
			return;
		}

		if ($file_size <= 0) {
			$this->template->content_display(lang('upload_size_exception','tip'));
			return;
		}

		// Validate file extension
		//$path_info = pathinfo($_FILES[$upload_name]['name']);
		//$file_extension = $path_info["extension"];
		$file_extension = strtolower(fileext($_FILES[$upload_name]['name']));
		$is_valid_extension = false;
		foreach ($extension_whitelist as $extension) {
			if (strcasecmp($file_extension, $extension) == 0) {
				$is_valid_extension = true;
				break;
			}
		}
		if (!$is_valid_extension) {
			$this->template->content_display(lang('upload_invalid_ext','tip'));
			return;
		}

		$file_path = $save_path.$file_name.'.'.$file_extension;
		if (!@move_uploaded_file($_FILES[$upload_name]["tmp_name"], $file_path)) {
			$this->template->content_display(lang('upload_save_faild','tip'));
			return;
		}

		$db_file_name = preg_replace('/[^'.$valid_chars_regex.']|\.+$/i', "", basename($_FILES[$upload_name]['name']));
		if (strlen($db_file_name) == 0 || strlen($db_file_name) > $MAX_FILENAME_LENGTH) {
			$db_file_name = $file_name.'.'.$file_extension;
		}

		$data['isimage']=in_array($file_extension, array('jpg','jpeg','png','gif'))?1:0;
		if($data['isimage']){
			$img_pro = @getimagesize($file_path);
			$data['width']=$img_pro['0'];
			$data['height']=$img_pro['1'];
		}
		$data['filename']=$db_file_name;
		$data['filesize']=$file_size;
		$data['attachment']=$date_dir.$file_name;
		$data['user_id']=$userid;
		$data['fileext']=$file_extension;
		$data['remote']=0;
		$data['description']='';
		$data['thumb']=0;
		$attachfile = $date_dir.$file_name.'.'.$file_extension;
		$api = load_api('attachment');
		$aid = $api->insertUnused($data);
		$this->template->content_display("FILEID:".$aid.'|'.$file_name.'|'.$attachfile.'|'.$db_file_name.'|'.$data['isimage'].'|'.$file_extension);
		return;
	}

}



